<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-form-item label="权限" prop="authorityType">
          <el-select v-model="queryParams.authorityType" class="width-120" placeholder="请选择" @change="handleQuery">
            <el-option v-if="userInfo.customerType != '3'" label="所有" value="">所有</el-option>
            <el-option v-for="dict in dictDataMap[
                    'template_authority_type'
                ]" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称" prop="title">
          <el-input v-model="queryParams.title" clearable placeholder="请输入模板主题名称" @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain type="primary" @click="handleAdd">
          <template #icon>
            <i-ep-plus/>
          </template>
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button :disabled="multiple" plain type="danger" @click="handleDelete">
          <template #icon>
            <i-ep-delete/>
          </template>
          删除
        </el-button>
      </el-col>
    </el-row>
    <el-table v-adaptive :border="true" :data="templateMasterList" :header-cell-style="$headerCellStyle" :stripe="true"
              highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column :align="'center'" type="selection" width="55"/>
      <el-table-column :align="'center'" label="模板主题名称" min-width="150" prop="title">
        <template #default="scope">
          <span class="ys-css">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="权限" prop="authorityType">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['template_authority_type']" :value="scope.row.authorityType"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="模板归属人" prop="userName"/>
      <el-table-column :align="'center'" label="模板类型" prop="type">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['template_type']" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="适用科室" prop="deptName"/>
      <el-table-column :align="'center'" label="是否启用" prop="startFlag">
        <template #default="scope">
          <el-switch
            v-model="scope.row.startFlag"
            active-text="是" inactive-text="否"
            inline-prompt
            @change="startFlagChange($event,scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="创建人" prop="createByName"/>

      <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="220"
      >
        <template #default="scope">
          <el-tooltip class="item" content="维护模板详情" effect="dark" placement="left">
            <el-button circle type="primary" @click="editTemplateDetail(scope.row)">
              <template #icon>
                <svg-icon icon-class="detail"/>
              </template>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" content="修改" effect="dark" placement="top">
            <el-button circle type="success" @click="handleUpdate(scope.row)">
              <template #icon>
                <i-ep-edit/>
              </template>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" content="删除" effect="dark" placement="top">
            <el-button circle type="danger" @click="handleDelete(scope.row)">
              <template #icon>
                <i-ep-delete/>
              </template>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total"
                @pagination="getList"/>

    <!-- 添加或修改价表对话框 -->
    <el-dialog v-model="open" :close-on-click-modal="false" append-to-body style="margin-bottom: 0" title="模板维护"
               width="400">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="是否启用" style="width: 100%">
          <el-radio-group v-model="form.startFlag">
            <el-radio-button v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                             :value="dict.dictValue">{{
                dict.dictLabel
              }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限" prop="authorityType">
          <el-select v-model="form.authorityType">
            <el-option v-for="dict in dictDataMap[
                                'template_authority_type'
                            ]" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入模板名称" @input="titleInput"/>
        </el-form-item>
        <el-form-item label="适用科室" prop="deptId">
          <base-dept-tree :org-id="form.orgId" :value="form.deptId" style="width: 100%;"
                          @deptSelect="deptSelect"/>
        </el-form-item>
        <!--        <el-form-item label="发药药房" prop="storageId">-->
        <!--          <el-select v-model="form.storageId" placeholder="请输入发药药房">-->
        <!--            <el-option v-for="drugVsDept in drugVsDeptList" :key="drugVsDept.id"-->
        <!--                       :label="drugVsDept.storageName" :value="drugVsDept.id"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 模板明细弹出框 -->
    <el-dialog v-model="detailOpen" :close-on-click-modal="false" append-to-body style="margin-bottom: 0" @close="detailCancel"
               title="模板详情维护"
               width="90%">
      <template #header>
        <div style="cursor: move">
          <el-row :gutter="10">
            <el-col :span="10">
              模板标题：<span style="color: #ff8c00">{{ currentRow.title }}</span>
            </el-col>
            <el-col :span="5">
              模板类型：<span style="color: #ff8c00">
              <dict-data-tag :options="dictDataMap['template_type']" :value="currentRow.type"
                             style="margin-left: 80px; margin-top: -22px;"/></span>
            </el-col>
            <el-col :span="5">
              权限：<span style="color: #ff8c00">
              <dict-data-tag :options="dictDataMap['template_authority_type']"
                             :value="currentRow.authorityType"
                             style="margin-left: 50px; margin-top: -21px;"/></span>
            </el-col>
            <el-col :span="4">
              适用科室：<span style="color: #ff8c00">{{ currentRow.deptName }}</span>
            </el-col>
          </el-row>
        </div>
      </template>
      <el-row style="height: 100%;padding-top: 30px;">
        <template-detail ref="templateDetailRef" :org-id="queryParams.orgId"
                         :dept-id="currentRow.deptId" :template-master-id="currentRow.templateMasterId"/>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
<!--            <el-button type="primary" @click="detailSubmitForm">确 定</el-button>-->
            <el-button @click="detailCancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>

import {useDictStoreHook} from "@/store/modules/dict.ts";
import {useUserStoreHook} from "@/store/modules/user.ts";

import {
  addTemplateMaster,
  delTemplateMaster,
  getTemplateMaster,
  selectPageTemplateMaster,
  updateTemplateMaster
} from "@/api/patient/templateMaster.ts";
import {getDrugVsDeptList} from "@/api/drug/drugStorageDept.ts";
import {firstLetterResult} from "@/utils/pinyin.ts";
import TemplateDetail from "@/views/template/wholeSet/templateDetail.vue";


const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const {proxy} = getCurrentInstance() as any;
const templateMasterList = ref([]);
const multiple = ref(true);
const total = ref(0);
const ids = ref([]);
// 添加或修改价表对话框
const open = ref(false);
//模板明细弹出框
const detailOpen = ref(false);
const formRef = ref();
const templateDetailRef = ref();
// 药房list
const drugVsDeptList = ref<any>([])
const queryParams = ref<any>({
  orgId: userInfo.orgId,
  type: "0"
})

// 当前选中的模板列表行
const currentRow = ref<any>({})
const dictStore = useDictStoreHook();
let dictDataMap = ref(
  dictStore.isTypeGetData(
    "template_type",
    "sys_yes_no",
    "template_authority_type",
    "bill_item_class_dict"
  )
);

const form = ref<TemplateMasterType>({
  templateMasterId: "",
  type: "0",
  authorityType: "0",
  title: "",
  titleInput: "",
  deptId: "",
  deptName: "",
  // storageId: "",
  startFlag: "Y",
  // itemClass: "",
  orgId: queryParams.value.orgId
});
const rules = {
  authorityType: [{required: true, message: "权限不能为空", trigger: "change",},],
  title: [{required: true, message: "模板主题名称不能为空", trigger: "blur",},],
  startFlag: [{required: true, message: "状态不能为空", trigger: "blur",},],
  deptId: [{required: true, message: "科室不能为空", trigger: "blur",},],
  // storageId: [{required: true, message: "发药药房不能为空", trigger: "blur",},],
};


// 以科室id查询对应的药房、药库信息
function getDrugVsDeptListFun() {
  let data = {
    deptId: form.value.deptId,
    orgId: userInfo.orgId,
    clinicOrVisitArray: proxy.$stringToArray("4,2,0", ","),
    storageTypeArray: proxy.$stringToArray("2,4", ","),
    drugGrantTypeArray: proxy.$stringToArray("1", ","),
  }
  getDrugVsDeptList(data).then((res: any) => {
    drugVsDeptList.value = res.data
  })
}

// 科室点击事件
function deptSelect(node) {
  form.value.deptId = node.deptId
  form.value.deptName = node.deptName
  getDrugVsDeptListFun()
}


function handleAdd() {
  resetForm()
  open.value = true;
}

function handleUpdate(row: any) {
  resetForm()
  open.value = true;
  getTemplateMaster(row.templateMasterId).then((res: any) => {
    form.value = res.data
  })
}

/**
 * 维护模板详情
 */
function editTemplateDetail(row: any) {
  currentRow.value = row
  detailOpen.value = true;
  nextTick(() => {
    templateDetailRef.value.setActive()
  })
}

function handleQuery() {
  getList()
}

function resetQuery() {
  getList()
}

function handleDelete(row) {
  delTemplateMaster(row.templateMasterId).then(() => {
    ElMessage.success("删除成功")
  })
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.templateMasterId);
  multiple.value = !selection.length;
}

/** 查询模板主记录列表 */
function getList() {
  selectPageTemplateMaster(queryParams.value).then((response: any) => {
    templateMasterList.value = response.rows;
    templateMasterList.value.forEach((item: any) => {
      item.startFlag = item.startFlag === "Y";
    })
    total.value = response.total;
  });
}

// 主题生成拼音码
function titleInput(value) {
  if (value) {
    form.value.titleInput = firstLetterResult(value)
  } else {
    form.value.titleInput = ""
  }
}

function tabClick(obj: any) {
  const objThis = toRaw(obj)
  if (objThis.props.name === '1') {
    nextTick(() => {
    })
  }
}

function startFlagChange(value, row: any) {
  const params = {
    templateMasterId: row.templateMasterId,
    startFlag: value ? "Y" : "N",
  }
  updateTemplateMaster(params).then(() => {
    ElMessage.success(`${value ? '启用成功' : '停用成功'}`)
  })
}

/**
 * 提交保存事件
 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      debugger
      if (form.value.templateMasterId != "") {
        updateTemplateMaster(form.value)
          .then(() => {
            ElMessage.success("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
          });
      } else {
        addTemplateMaster(form.value)
          .then(() => {
            ElMessage.success("新增成功");
            open.value = false;
            getList();
          })
          .finally(() => {
          });
      }
    }
  })
}

/**
 * 模板主记录弹出框关闭事件
 */
function cancel() {
  resetForm()
  open.value = false
}

/**
 * 模板明细弹出框关闭事件
 */
function detailCancel() {
  nextTick(()=>{
    templateDetailRef.value.clearFormAll()
  })
  detailOpen.value = false;
}

/**
 * 清空表单
 */
function resetForm() {
  form.value.templateMasterId = ""
  form.value.type = "0"
  form.value.authorityType = "0"
  form.value.title = ""
  form.value.titleInput = ""
  form.value.deptId = ""
  form.value.deptName = ""
  // storageId: "",
  form.value.startFlag = "Y"
  // itemClass: "",
  form.value.orgId = queryParams.value.orgId
}

getList()
</script>
<script lang="ts">
export default {
  name: "WholeSet"
}
</script>
<style scoped>

:deep(.el-dialog__body) {
  padding-top: 20px !important;
}
</style>
